package com.learn.jpatest.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.jpatest.model.BaseNote;
import com.learn.jpatest.model.Note;
import com.learn.jpatest.model.OtherNote;
import com.learn.jpatest.repository.BaseNoteRepository;
import com.learn.jpatest.repository.NoteRepository;
import com.learn.jpatest.repository.OtherNoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Map;

@Service
public class NoteService {

    @Autowired
    NoteRepository noteRepository;

    @Autowired
    OtherNoteRepository otherNoteRepository;

    private static ObjectMapper objectMapper = new ObjectMapper();

    public BaseNote createNote(Map noteMap, String tableName) {
        BaseNoteRepository repository = this.repositoryFromTableName(tableName);
        BaseNote baseNote = this.convertNote(noteMap, tableName);
        return (BaseNote) repository.save(baseNote);
    }

    public Dict getNoteById(Long noteId, String tableName) {
        BaseNoteRepository repository = this.repositoryFromTableName(tableName);
        BaseNote note = (BaseNote) repository.findById(noteId).orElse(null);
        return Dict.create().set("code", 200).set("data", note);
    }

    private BaseNote convertNote(Map noteMap, String tableName) {
        BaseNote baseNote = null;
        if ("note".equals(tableName)) {
            baseNote = objectMapper.convertValue(noteMap, Note.class);
        } else {
            baseNote = objectMapper.convertValue(noteMap, OtherNote.class);
        }
        return baseNote;
    }

    private BaseNoteRepository repositoryFromTableName(String tableName) {
        BaseNoteRepository repository = null;
        if ("note".equals(tableName)) {
            repository = noteRepository;
        } else {
            repository = otherNoteRepository;
        }
        return repository;
    }
}
